package com.ruicar.afs.cloud.gateway.config;

import com.ruicar.afs.cloud.gateway.filter.RequestFilterHandler;
import com.ruicar.afs.cloud.gateway.handler.*;
import lombok.AllArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.MediaType;
import org.springframework.web.reactive.function.server.RequestPredicates;
import org.springframework.web.reactive.function.server.RouterFunction;
import org.springframework.web.reactive.function.server.RouterFunctions;

/**
 * @author Fzero
 * @date 2019-01-24
 * 路由配置信息
 */
@Slf4j
@Configuration
@AllArgsConstructor
public class RouterFunctionConfiguration {
	private final SentinelFallbackHandler sentinelFallbackHandler;
	private final SwaggerResourceHandler swaggerResourceHandler;
	private final SwaggerSecurityHandler swaggerSecurityHandler;
	private final SwaggerUiHandler swaggerUiHandler;
	private final CaptchaCodeHandler captchaCodeHandler;
	private final AfsLoginHandler afsLoginHandler;
	private final AfsRefreshTokenHandler afsRefreshTokenHandler;
	private final SystemRsaPublicKeyHandler rsaPublicKeyHandler;
	private final RequestFilterHandler requestFilterHandler;

	@Bean
	public RouterFunction routerFunction() {
		return RouterFunctions.route(
				RequestPredicates.path("/fallback")
						.and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), sentinelFallbackHandler)
				.andRoute(RequestPredicates.GET("/captcha")
						.and(RequestPredicates.accept(MediaType.TEXT_PLAIN)), captchaCodeHandler)
				.andRoute(RequestPredicates.GET("/swagger-resources")
						.and(RequestPredicates.accept(MediaType.ALL)), swaggerResourceHandler)
				.andRoute(RequestPredicates.GET("/swagger-resources/configuration/ui")
						.and(RequestPredicates.accept(MediaType.ALL)), swaggerUiHandler)
				.andRoute(RequestPredicates.GET("/swagger-resources/configuration/security")
						.and(RequestPredicates.accept(MediaType.ALL)), swaggerSecurityHandler)
				.andRoute(RequestPredicates.POST("/userlogin")
						.and(RequestPredicates.accept(MediaType.APPLICATION_FORM_URLENCODED)), afsLoginHandler)
				.andRoute(RequestPredicates.POST("/refreshtoken")
						.and(RequestPredicates.accept(MediaType.APPLICATION_FORM_URLENCODED)), afsRefreshTokenHandler)
				.andRoute(RequestPredicates.GET("/pubkey")
						.and(RequestPredicates.accept(MediaType.APPLICATION_FORM_URLENCODED)), rsaPublicKeyHandler)
				.filter(requestFilterHandler)
				;
	}

}
